﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;

namespace DemoPersonalizeSearch
{
    public static class ParseData
    {
        public static void ParseLinkData(this  WResultItem ri, LinkData ld)
        {
            ri.Title = ld.Title;
            ri.Url = ld.URL;
            ri.DateModified = (DateTime)ld.DateModified;
            string str = ld.TagData;
            List<TagItem> list = new List<TagItem>();
            string[] arrTags = str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            //string s = "tun!@#$%^&*()g"; 
            Regex p = new Regex(@"\S*<<");
            Regex p1 = new Regex(@"<<\d+>>");
            foreach (var s in arrTags)
            {
                string chuoi = s.Trim();
                
                //get tagname
                string tagname = p.Match(chuoi).Value;
                if (tagname != "" && tagname != " ")
                tagname = tagname.Substring(0, tagname.Length - 2);
                else
                tagname = chuoi;
                int w =1;
                string weight = p1.Match(chuoi).Value;
                if (weight != "")
                { 
                    weight = weight.Substring(2,weight.Length-4);
                }
                int.TryParse(weight, out w);
                if (w == 0) w = 1;
                TagItem t = new TagItem(tagname,w);
                list.Add(t);

            }
            list = list.GroupBy(x=>x.TagName.ToLower()).Select(x=>new TagItem(x.Key,x.Sum(y=>y.Weight))).ToList();
            ri.Tags = list;
        }
        public static void ParseUserData(this UserItem ui, UserData ud)
        {
            JObject obj = JObject.Parse(ud.TagData);
            List<TagItem> list = new List<TagItem>();
            foreach (var p in obj.Properties())
            {
                TagItem t = new TagItem(p.Name, (double)p.Value);
                list.Add(t);
            }
            ui.Username = ud.Username;
            ui.Tags = list;
        }
    }
}
